﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Domain.Entities
{
    public class IPAddressV4
    {
        byte[] _ipV4 = new byte[4];
        public byte[] Value
        {
            get { return _ipV4; }
        }
        private IPAddressV4(byte[] ipV4)
        {
            _ipV4 = ipV4;
        }
        public static IPAddressV4 Create(string arg)
        {
            IPAddressV4 ipV4;
            if (TryParse(arg, out ipV4))
            {
                return new IPAddressV4(ipV4.Value);
            }
            else
            {
                return null;
            }
        }
        public static bool TryParse(string arg, out IPAddressV4 ipV4)
        {
            arg = arg.Trim();
            string pattern = @"^(?<o1>\d{1,3})\.(?<o2>\d{1,3})\.(?<o3>\d{1,3})\.(?<o4>\d{1,3})$";
            Match m = Regex.Match(arg, pattern);
            if (m.Success)
            {
                Byte[] tempBytesIpV4 = new byte[4];
                if (Byte.TryParse(m.Groups["o1"].Value, out tempBytesIpV4[0]) &&
                    Byte.TryParse(m.Groups["o2"].Value, out tempBytesIpV4[1]) &&
                    Byte.TryParse(m.Groups["o3"].Value, out tempBytesIpV4[2]) &&
                    Byte.TryParse(m.Groups["o4"].Value, out tempBytesIpV4[3]))
                {
                    if (tempBytesIpV4[0] != 0)
                    {
                        ipV4 = new IPAddressV4(tempBytesIpV4);
                        return true;
                    }
                }
            }
            ipV4 = null;
            return false;
        }
        public override string ToString()
        {
            return String.Format("{0}.{1}.{2}.{3}", _ipV4[0], _ipV4[1], _ipV4[2], _ipV4[3]);
        }
    }
}
